﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using API;
using API.StoreWebService;
using DB;

namespace ProductManage
{
    public partial class FormMagentGoProducts : Form
    {
        private ProductsDb _db = ProductsDb.DbMysql;
        public FormMagentGoProducts()
        {
            InitializeComponent();
        }

        #region 连数据库数据操作

        #region 添加新产品
        private void buttonAddProduct_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            List<string> onlineSkuList = new List<string>();
            foreach (var product in list)
            {
                if(!onlineSkuList.Contains(product.SKU))
                    StoreApi.Api.CreateProduct(product);
            }
        }
        private int index = 0;
        private void buttonUpload_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            foreach (var product in list)
            {
                StoreApi.Api.UpdateProduct(product);
            }
        }
        private void buttonDownLoad_Click(object sender, EventArgs e)
        {
            foreach (var product in _onlineListProucts)
            {
                SaveProductCategorysToDB(product.sku, product.category_ids,1);
            } 
        }

        private void SaveProductCategorysToDB(string sku, string[] category_ids,int status)
        {
            var entities = new PugsterEntities();
            string categorys = "";
            foreach (var category in category_ids)
            {
                categorys += category + ",";
            }
            categorys = categorys.TrimEnd(',');

            var productCategorys = from p in entities.CategoryProducts
                                   where p.SKU == sku
                                   select p;

            if (productCategorys.Count() > 0)
            {
                if (productCategorys.First().Categorys != categorys)
                {
                    productCategorys.First().Categorys = categorys;
                    productCategorys.First().Status = status;
                }
            }
            else
            {
                entities.CategoryProducts.Add(new CategoryProduct()
                {
                    Categorys = categorys,
                    SKU = sku,
                    Status = status
                });
            }
            entities.SaveChanges();
        }

        private string[] GetDownLoadAttribute()
        {
            List<string> listAdditionalAttributes = new List<string>();
            foreach (DataGridViewRow row in this.dataGridViewAttribute.Rows)
            {
                if ((bool)row.Cells[0].Value)
                {
                    catalogAttributeEntity catalogAttributeEntity = row.Tag as catalogAttributeEntity;
                    listAdditionalAttributes.Add(catalogAttributeEntity.code.ToString());
                }
            }
            return listAdditionalAttributes.ToArray();
        }
        #endregion

        #region 更新图片
        private void button2_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            int i = 0;
            foreach (var product in list)
            {
                i++;
                StoreApi.Api.ReSetProductImage(product);
                //StoreApi.Api.UpdateProduct(product);
            }
        }
        #endregion

        private Product[] GetUploadList()
        {
            var strAll2Upload = this.textBox1.Text;
            var skulist = strAll2Upload.Split('\n', '\t', ' ','\r');
            var entities = new PugsterEntities();
            var listProduct = _db.GetAllProducts();
            var list = from p in listProduct
                     where skulist.Contains(p.SKU)
                     select p;
            index = 0;
            return list.ToArray();
        }


        private void button4_Click(object sender, EventArgs e)
        {

            this.textBox5.Text = (Convert.ToInt32(this.textBox5.Text) + 1).ToString();
            buttonLoadProductCategory_Click(null, null);
        }
        private void buttonLoadProductCategory_Click(object sender, EventArgs e)
        {
            if (this.treeViewCategory.Nodes.Count == 0)
            {
                LoadCategoryTree(this.treeViewCategory);
            }
            var entities = new PugsterEntities();
            var productCategorys = (from p in entities.CategoryProducts orderby p.SKU
                                    select p ).Skip(20 * Convert.ToInt32(textBox5.Text)).Take(20).ToList();
            this.dataGridViewProductCategory.Rows.Clear();
            foreach (var productCategory in productCategorys)
            {
                var images = ProductImageApi.GetImages(productCategory.SKU);
                Image image = null;
                if (images.Count > 0)
                {
                    image = images[0];
                }
                var strCategorys = "";
                foreach (var category in productCategory.Categorys.Split(','))
                {
                    foreach (catalogCategoryEntity node in this.checkedListBox2.Items)
                    {
                        if (string.IsNullOrEmpty(category))continue;
                        if (node.category_id == Convert.ToInt32(category))
                        {
                            strCategorys += node.name + ",";
                            break;
                        }
                    }
                    
                }
                int index = this.dataGridViewProductCategory.Rows.Add(new object[] { image, strCategorys.TrimEnd(',') });
                this.dataGridViewProductCategory.Rows[index].Tag = productCategory;
            }
        }

        private void buttonRemoveCategory_Click(object sender, EventArgs e)
        {
            var entities = new PugsterEntities();
            var productCategorys = (from p in entities.CategoryProducts
                                   where p.Status == 0 && !string.IsNullOrEmpty(p.Categorys)
                                    select p).Take(50).ToList();
            foreach (var productCategory in productCategorys)
            {
                StoreApi.Api.AssignProduct2Category(productCategory.SKU, productCategory.Categorys.Split(','));
                productCategory.Status = 1;
            }
            entities.SaveChanges();
        }

        private void dataGridViewProductCategory_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewProductCategory.SelectedRows.Count == 0) return;
            var productCategorys = this.dataGridViewProductCategory.SelectedRows[0].Tag as CategoryProduct;

            List<string> categorys = new List<string>();
            categorys = productCategorys.Categorys.Split(',').ToList();

            this.checkedListBox2.ItemCheck -= checkedListBox2_ItemCheck;
            for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
            {
                catalogCategoryEntity item = this.checkedListBox2.Items[i] as catalogCategoryEntity;
                this.checkedListBox2.SetItemChecked(i, categorys.Contains(item.category_id.ToString()));
            }
            this.checkedListBox2.ItemCheck += checkedListBox2_ItemCheck;
        }
        private void checkedListBox2_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            catalogCategoryEntity catalogCategoryEntity = this.checkedListBox2.Items[e.Index] as catalogCategoryEntity;
            foreach (DataGridViewRow row in this.dataGridViewProductCategory.SelectedRows)
            {
                var CategoryProduct = row.Tag as CategoryProduct;
                if (CategoryProduct != null && catalogCategoryEntity != null)
                {
                    var categorys = new List<string>();
                    foreach (catalogCategoryEntity checkedItem in this.checkedListBox2.CheckedItems)
                    {
                        categorys.Add(checkedItem.category_id.ToString());
                    }
                    if (e.NewValue == CheckState.Checked)
                    {
                        categorys.Add(catalogCategoryEntity.category_id.ToString());
                    }
                    else
                    {
                        if (categorys.Contains(catalogCategoryEntity.category_id.ToString()))
                        {
                            categorys.Remove(catalogCategoryEntity.category_id.ToString());
                        }
                    }

                    SaveProductCategorysToDB(CategoryProduct.SKU, categorys.ToArray(), 0);
                }
            }
        }


        Dictionary<string, string> dicStock = new Dictionary<string, string>();
        List<Product> listProductInfo;
        private int ilistProductInfo = 0;
        private void button5_Click(object sender, EventArgs e)
        {
            this.webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_LoadProductStock;
            this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted_LoadProductStock;
            listProductInfo = _db.GetAllProducts();

            deal(listProductInfo[ilistProductInfo++].EbaoURL);
            
             dicStock = new Dictionary<string, string>();
       }
        private void deal(string strUrl)
        {
            this.webBrowser1.Url = new Uri(strUrl);
        }
        void webBrowser1_DocumentCompleted_LoadProductStock(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                try
                {
                    var document = webBrowser1.Document;
                    var detail = GetProductDetail(document);
                    if (detail.ContainsKey("编号"))
                    {
                        var invertory = detail["库存"];
                        var code = detail["编号"];
                        if (listProductInfo[ilistProductInfo -1].SKU == code)
                        {
                            if (!dicStock.ContainsKey(code))
                            {
                                dicStock.Add(code, invertory);
                                if (invertory == "有货" && listProductInfo[ilistProductInfo - 1].EbaoInventory==0)
                                {
                                    listProductInfo[ilistProductInfo - 1].EbaoInventory = 999;
                                    ProductsDb.DbMysql.UpdateProduts(listProductInfo[ilistProductInfo - 1]);
                                }
                                else if (invertory != "有货" && listProductInfo[ilistProductInfo - 1].EbaoInventory != 0)
                                {
                                    listProductInfo[ilistProductInfo - 1].EbaoInventory = 0;
                                    ProductsDb.DbMysql.UpdateProduts(listProductInfo[ilistProductInfo - 1]);
                                }

                                if (listProductInfo[ilistProductInfo - 1].Status[0] == 49)
                                    StoreApi.Api.UpdateProductStock(listProductInfo[ilistProductInfo - 1].EbaoInventory > 0, code);
                            }
                        }
                    }
                    if (ilistProductInfo < listProductInfo.Count)
                        deal(listProductInfo[ilistProductInfo++].EbaoURL);
                    else
                    {
                        StoreApi.Api.RefreshCatalog();
                        this.Text = "Done";
                    }
                }
                catch (Exception exception)
                {
                    if (ilistProductInfo < listProductInfo.Count)
                        deal(listProductInfo[ilistProductInfo++].EbaoURL);
                    else
                    {
                        StoreApi.Api.RefreshCatalog();
                        this.Text = "Done";
                    }
                    //MessageBox.Show(exception.Message);
                }

            }
        }

        private Dictionary<string, string> GetProductDetail(HtmlDocument strHtml)
        {
            var infos = strHtml.GetElementById("form1");
            Dictionary<string, string> list = new Dictionary<string, string>();
            try
            {
                if (infos == null)
                    return list;
                var text = infos.InnerText;
                StringReader reader = new StringReader(text);
                var strLine = reader.ReadLine();
                while (!string.IsNullOrEmpty(strLine))
                {
                    if (strLine.Contains("："))
                    {
                        var t = strLine.Split('：');
                        if (!list.ContainsKey(t[0]))
                        {
                            list.Add(t[0].Trim(), t[1].Trim());
                        }
                    }
                    strLine = reader.ReadLine();
                }
            }
            catch (Exception)
            {
            }

            return list;
        }
        private void button6_Click(object sender, EventArgs e)
        {

            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            foreach (var product in list)
            {
                try
                {
                    StoreApi.Api.SetProductNewest(product.SKU);
                }
                catch (Exception)
                {
                }
            }
        }
        #endregion
        
        
        private string strPath = @"\\tsclient\G";
        private bool copeImage(string imageName,string saveName)
        {
            
            string localPath = strPath + @"\Image\" + imageName;
            if (!File.Exists(localPath))
                localPath = strPath + @"\Image1\" + imageName;
            if (!File.Exists(localPath))
                localPath = strPath + @"\Image2\" + imageName;
            if (!File.Exists(localPath))
                localPath = strPath + @"\Image3\" + imageName;
            if (File.Exists(localPath))
            {
                File.Copy(localPath, @"\\pig\Images\Products\" + saveName, true);
                return true;
            }
            else
            {
                return false;
            }
        }

        #region 加载线上数据
        private catalogProductEntity[] _onlineListProucts;
        private void buttonLoadOnlineData_Click(object sender, EventArgs e)
        {
            LoadProducts();
            LoadAtrribute();
            InitializeDataGridViewProductsColumns();
        }
        private void LoadProducts()
        {
            LoadCategoryTree(this.treeViewCategory);
            _onlineListProucts = StoreApi.Api.GetOnlineProductList();
        }
        private void LoadCategoryTree(TreeView treeView)
        {
            this.checkedListBox1.Items.Clear();
            this.checkedListBox1.DisplayMember = "name";
            this.checkedListBox2.Items.Clear();
            this.checkedListBox2.DisplayMember = "name";
            treeView.Nodes.Clear();
            var tree = StoreApi.Api.GetCategory();
            var node = treeView.Nodes.Add("1", "Main");

            foreach (var child in tree.children)
            {
                var childnode = node.Nodes.Add(child.category_id.ToString(), child.name);
                childnode.Tag = child;
                this.checkedListBox1.Items.Add(child, false);
                this.checkedListBox2.Items.Add(child, false);
                if (child.children.Count() > 0)
                {
                    FillNode(child, childnode);
                }
            } 
        }
        private void FillNode(catalogCategoryEntity nodeOnline, TreeNode node)
        {
            foreach (var child in nodeOnline.children)
            {
                var childnode = node.Nodes.Add(child.category_id.ToString(), child.name);
                childnode.Tag = child;
                this.checkedListBox1.Items.Add(child, false);
                this.checkedListBox2.Items.Add(child, false);
                if (child.children.Count() > 0)
                {
                    FillNode(child, childnode);
                }
            }
        }
        private void LoadAtrribute()
        {
            var attributeList = StoreApi.Api.GetAttributelist();
            dataGridViewAttribute.Rows.Clear();
            int index = 0;
            foreach (var catalogAttributeEntity in attributeList)
            {
                index = dataGridViewAttribute.Rows.Add(index < 10, catalogAttributeEntity.code);
                dataGridViewAttribute.Rows[index].Tag = catalogAttributeEntity;
            }
        }
        #endregion

        #region 数据显示
        private Dictionary<catalogProductEntity, catalogProductReturnEntity> _dicCatalogProductReturnEntity = new Dictionary<catalogProductEntity, catalogProductReturnEntity>();

        private catalogProductReturnEntity GetcatalogProductReturnEntity(catalogProductEntity catalogProductEntity)
        {
            if (_dicCatalogProductReturnEntity.ContainsKey(catalogProductEntity))
                return _dicCatalogProductReturnEntity[catalogProductEntity];
            var productinfo = StoreApi.Api.GetProductInfo(catalogProductEntity, _additionalAttributes);
            _dicCatalogProductReturnEntity.Add(catalogProductEntity, productinfo);
            return _dicCatalogProductReturnEntity[catalogProductEntity];
        }

        private void treeViewCategory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var catalogCategoryEntity = e.Node.Tag as catalogCategoryEntity;
            if (catalogCategoryEntity == null) return;
            ShowProduts(catalogCategoryEntity.category_id.ToString(),0,10,this.textBox3.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShowProduts(_strCategoryid, 10 * (Convert.ToInt32(this.textBox2.Text) - 1), 10 * Convert.ToInt32(this.textBox2.Text),this.textBox3.Text);
        }
        private void buttonNextPage_Click(object sender, EventArgs e)
        {
            this.textBox2.Text = (Convert.ToInt32(this.textBox2.Text) + 1).ToString();
            ShowProduts(_strCategoryid, 10 * (Convert.ToInt32(this.textBox2.Text) - 1), 10 * Convert.ToInt32(this.textBox2.Text), this.textBox3.Text);
        }
        private string _strCategoryid = null;
        private bool CheckKeyword(string strkeyWord, catalogProductEntity catalogProductEntity)
        {
            if (catalogProductEntity == null) return false;
            if (string.IsNullOrEmpty(strkeyWord)) return true;
            if (catalogProductEntity.name.Contains(strkeyWord)) return true;
            return false;
        }
        private void ShowProduts(string strCategoryid, int iStart,int iEnd, string strkeyWord)
        {
            _strCategoryid = strCategoryid;
            this.dataGridViewProducts.Rows.Clear();
            int i = -1;
            if (strCategoryid == null)
            {
                foreach (var catalogProductEntity in _onlineListProucts)
                {
                    if (catalogProductEntity.category_ids.Count() == 0)
                    {
                        if (!CheckKeyword(strkeyWord, catalogProductEntity)) continue;
                        i = i + 1;
                        if (i < iStart) continue;
                        if (i > iEnd) continue;
                        var productinfo = GetcatalogProductReturnEntity(catalogProductEntity);
                        int index = this.dataGridViewProducts.Rows.Add(new DataGridViewRow());
                        this.dataGridViewProducts.Rows[index].Tag = productinfo;
                        foreach (DataGridViewCell cell in this.dataGridViewProducts.Rows[index].Cells)
                        {
                            SetCellValue(cell, productinfo);
                        }
                        Application.DoEvents();
                    }
                }
            }
            else
            {
                foreach (var catalogProductEntity in _onlineListProucts)
                {
                    if (catalogProductEntity.category_ids.ToList().Contains(strCategoryid))
                    {
                        if (!CheckKeyword(strkeyWord, catalogProductEntity)) continue;
                        i = i + 1;
                        if (i < iStart) continue;
                        if (i > iEnd) continue;
                        var productinfo = GetcatalogProductReturnEntity(catalogProductEntity);
                        int index = this.dataGridViewProducts.Rows.Add(new DataGridViewRow());
                        this.dataGridViewProducts.Rows[index].Tag = productinfo;
                        foreach (DataGridViewCell cell in this.dataGridViewProducts.Rows[index].Cells)
                        {
                            SetCellValue(cell, productinfo);
                        }

                    }
                }
            }
        }
        private void SetCellValue(DataGridViewCell cell, catalogProductReturnEntity productinfo)
        {
            //Type type = productinfo.GetType();
            //var properties = type.GetProperties();

            //foreach (var property in properties)
            //{
            //    if (property.Name.ToLower() == this.dataGridViewProducts.Columns[cell.ColumnIndex].Name.ToLower())
            //    {
            //        cell.Value = property.GetValue(productinfo, null);
            //        return;
            //    }
            //}
            if (this.dataGridViewProducts.Columns[cell.ColumnIndex].Name == "pic")
            {
                var images = ProductImageApi.GetImages(productinfo.sku);
                if (images.Count > 0)
                {
                    cell.Value = images[0];
                }
                return;
            }
            if (productinfo.additional_attributes == null) return;
            var catalogProductAttributeEntity = this.dataGridViewProducts.Columns[cell.ColumnIndex].Tag as catalogProductAttributeEntity;
            if (catalogProductAttributeEntity == null) return;
            foreach (var additional_attribute in productinfo.additional_attributes)
            {
                if (additional_attribute.key.ToLower() ==
                    catalogProductAttributeEntity.attribute_code.ToLower())
                {
                    if (catalogProductAttributeEntity.options == null)
                    {
                        cell.Value = additional_attribute.value;
                        return;
                    }
                    else
                    {
                        foreach (catalogAttributeOptionEntity catalogAttributeOptionEntity in catalogProductAttributeEntity.options)
                        {
                            if (catalogAttributeOptionEntity.value == additional_attribute.value)
                            {
                                cell.Value = catalogAttributeOptionEntity.label;
                                return;
                            }
                        }
                    }
                    return;
                }
            }
        }
        #endregion

        #region 设置显示属性
        private string[] _additionalAttributes ;
        private void InitializeDataGridViewProductsColumns()
        {
            _dicCatalogProductReturnEntity.Clear();
            
            List<string> listAdditionalAttributes = new List<string>();
            this.dataGridViewProducts.Columns.Clear();
            this.dataGridViewProducts.Columns.Add(new DataGridViewCheckBoxColumn() { Name = "Select", HeaderText = "", Selected = false, AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells });
            this.dataGridViewProducts.Columns.Add(new DataGridViewImageColumn() { Name = "pic", HeaderText = "",ImageLayout = DataGridViewImageCellLayout.Zoom, AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells });
            foreach (DataGridViewRow row in this.dataGridViewAttribute.Rows)
            {
                if ((bool)row.Cells[0].Value)
                {
                    catalogAttributeEntity catalogAttributeEntity = row.Tag as catalogAttributeEntity;
                    var info = StoreApi.Api.GetAttributeInfo(catalogAttributeEntity.attribute_id.ToString());
                    this.dataGridViewProducts.Columns.Add(info.attribute_code, info.attribute_code);
                    this.dataGridViewProducts.Columns[catalogAttributeEntity.code].Tag = info;
                    listAdditionalAttributes.Add(catalogAttributeEntity.code.ToString());
                }
            }
            _additionalAttributes = listAdditionalAttributes.ToArray();
        }
        private void buttonLoadAttribute_Click(object sender, EventArgs e)
        {
            InitializeDataGridViewProductsColumns();
        }
        private void dataGridViewProducts_Click(object sender, EventArgs e)
        {
            this.pictureBoxPic.Image = null;
            if (this.dataGridViewProducts.SelectedRows.Count == 0) return;
            var catalogProductReturnEntity = this.dataGridViewProducts.SelectedRows[0].Tag as catalogProductReturnEntity;
            var images = ProductImageApi.GetImages(catalogProductReturnEntity.sku);
            if(images.Count == 0)
                return;
            this.pictureBoxPic.Image = images[0];
            this.checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
            for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
            {
                catalogCategoryEntity item = this.checkedListBox1.Items[i] as catalogCategoryEntity;
                this.checkedListBox1.SetItemChecked(i, catalogProductReturnEntity.categories.Contains(item.category_id.ToString()));
            }
            this.checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
        }
        #endregion

        #region 编辑

        #region 设置编辑属性
        private void dataGridViewAttribute_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewProducts.Columns == null) return;
            
            if (this.dataGridViewAttribute.SelectedRows.Count == 0) return;

            var catalogAttributeEntity = this.dataGridViewAttribute.SelectedRows[0].Tag as catalogAttributeEntity;
            var column = this.dataGridViewProducts.Columns[catalogAttributeEntity.code];
            if (column == null) return;
            var catalogProductAttributeEntity = column.Tag as catalogProductAttributeEntity;
            if (catalogProductAttributeEntity.options == null)
            {
                this.richTextBoxAttrbute.Text = "";
                this.richTextBoxAttrbute.Visible = true;
                this.comboBoxAttrbute.Visible = false;
                this.checkedListBoxAttrbute.Visible = false;
            }
            else
            {
                this.comboBoxAttrbute.Items.Clear();
                this.comboBoxAttrbute.Text = "";
                foreach (catalogAttributeOptionEntity catalogAttributeOptionEntity in catalogProductAttributeEntity.options)
                {
                    this.comboBoxAttrbute.Items.Add(catalogAttributeOptionEntity.label);
                }
                this.richTextBoxAttrbute.Visible = false;
                this.comboBoxAttrbute.Visible = true;
                this.checkedListBoxAttrbute.Visible = false;
            }
        }
        #endregion

        private void buttonSetAttribute_Click(object sender, EventArgs e)
        {
            var catalogAttributeEntity = this.dataGridViewAttribute.SelectedRows[0].Tag as catalogAttributeEntity;
            foreach (DataGridViewRow row in this.dataGridViewProducts.Rows)
            {
                if (row.Cells[0].Value == null)continue;
                if ((bool)row.Cells[0].Value)
                {
                    catalogProductReturnEntity catalogProductReturnEntity = row.Tag as catalogProductReturnEntity;
                    row.Cells[catalogAttributeEntity.code].Value = this.comboBoxAttrbute.Text;
                    if (catalogProductReturnEntity.additional_attributes != null)
                    {
                        foreach (var additional_attribute in catalogProductReturnEntity.additional_attributes)
                        {
                            if (additional_attribute.key == catalogAttributeEntity.code)
                            {
                                var column = this.dataGridViewProducts.Columns[catalogAttributeEntity.code];
                                if (column == null) return;
                                var catalogProductAttributeEntity = column.Tag as catalogProductAttributeEntity;
                                foreach (var option in catalogProductAttributeEntity.options)
                                {
                                    if (option.label == this.comboBoxAttrbute.Text)
                                    {
                                        additional_attribute.value = option.value;
                                        StoreApi.Api.UpdateProductAdditionalAttributes(catalogProductReturnEntity.sku, catalogAttributeEntity.code, additional_attribute.value);
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region AssignCategory
        private void buttonNoCategory_Click(object sender, EventArgs e)
        {
            ShowProduts(null, 0, 10, this.textBox3.Text);
        }
        #endregion


        private int GetIndex(int ilink, int iLength)
        {
            int iRtn = ilink;
            while (iRtn >= iLength)
                iRtn = iRtn - iLength;
            while (iRtn < 0)
                iRtn = iRtn + iLength;
            return iRtn;
        }

        private void buttonUploadUpSell_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _onlineListProucts.Count(); i++)
            {
                int ilink = i*5;
                int ilink1 = GetIndex(ilink, _onlineListProucts.Count());
                int ilink2 = GetIndex(ilink + 1 , _onlineListProucts.Count());
                int ilink3 = GetIndex(ilink + 2, _onlineListProucts.Count());
                int ilink4 = GetIndex(ilink + 3, _onlineListProucts.Count());
                int ilink5 = GetIndex(ilink + 4, _onlineListProucts.Count());
      
                StoreApi.Api.RemoveProductUpSellLinks(_onlineListProucts[i].sku);
                StoreApi.Api.SetProductUpSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink1]);
                StoreApi.Api.SetProductUpSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink2]);
                StoreApi.Api.SetProductUpSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink3]);
                StoreApi.Api.SetProductUpSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink4]);
                StoreApi.Api.SetProductUpSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink5]);
            }

            for (int j = 0; j < _onlineListProucts.Count(); j++)
            {
                int ilink = j * 5;
                int ilink1 = GetIndex(ilink, _onlineListProucts.Count());
                int ilink2 = GetIndex(ilink - 1, _onlineListProucts.Count());
                int ilink3 = GetIndex(ilink - 2, _onlineListProucts.Count());
                int ilink4 = GetIndex(ilink - 3, _onlineListProucts.Count());
                int ilink5 = GetIndex(ilink - 4, _onlineListProucts.Count());
                StoreApi.Api.RemoveProductCrossSellLinks(_onlineListProucts[j].sku);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[j].sku, _onlineListProucts[ilink1]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[j].sku, _onlineListProucts[ilink2]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[j].sku, _onlineListProucts[ilink3]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[j].sku, _onlineListProucts[ilink4]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[j].sku, _onlineListProucts[ilink5]);
            }
        }

        private void buttonUploadCrossSell_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _onlineListProucts.Count(); i++)
            {
                int ilink = i * 5;
                int ilink1 = GetIndex(ilink, _onlineListProucts.Count());
                int ilink2 = GetIndex(ilink - 1, _onlineListProucts.Count());
                int ilink3 = GetIndex(ilink - 2, _onlineListProucts.Count());
                int ilink4 = GetIndex(ilink - 3, _onlineListProucts.Count());
                int ilink5 = GetIndex(ilink - 4, _onlineListProucts.Count());
                StoreApi.Api.RemoveProductCrossSellLinks(_onlineListProucts[i].sku);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink1]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink2]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink3]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink4]);
                StoreApi.Api.SetProductCrossSellLinks(_onlineListProucts[i].sku, _onlineListProucts[ilink5]);
            }

        }

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            var catalogProductReturnEntity = this.dataGridViewProducts.SelectedRows[0].Tag as catalogProductReturnEntity;
            catalogCategoryEntity catalogCategoryEntity = this.checkedListBox1.Items[e.Index] as catalogCategoryEntity;
            if (catalogProductReturnEntity != null && catalogCategoryEntity != null)
            {
                if (e.NewValue == CheckState.Checked)
                {
                    StoreApi.Api.AssignProduct2Category(catalogProductReturnEntity.sku,catalogCategoryEntity.category_id);
                    this.dataGridViewProducts.SelectedRows[0].Tag = StoreApi.Api.GetProductInfo(catalogProductReturnEntity.sku,this._additionalAttributes);
                }
                else
                {
                    StoreApi.Api.RemoveProductFromCategory(catalogProductReturnEntity.sku, catalogCategoryEntity.category_id);
                    this.dataGridViewProducts.SelectedRows[0].Tag = StoreApi.Api.GetProductInfo(catalogProductReturnEntity.sku, this._additionalAttributes);
                }

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            index = 0;
            foreach (var catalogProductEntity in list.ToList())
            {
                var images = ProductImageApi.GetImages(catalogProductEntity.SKU);
                index = 1;
                foreach (var image in images)
                {
                    if (image != null)
                        image.Save(@"C:\Images\Online\" + catalogProductEntity.SKU + "_PIC" + index++ + ".jpg");
                }
            }
        }

        private string MainTemple = "<html><head>  <link href=\"//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap.no-icons.min.css\" rel=\"stylesheet\"></head><body>  <div class=\"container\" style=\"width:810px; padding: 0;\">    {{products}}  </div></body></html>";

        private string ProductTemple =
            "<div class=\"row\" style=\"width:100%; background-color:#C9C9C9; padding:24px 10px;\">      <div class=\"span\" style=\"width: 100%; text-align:center;\">        <span style=\"display: inline-block; position: relative; background: white; border: 6px solid white; border-radius: 2px; box-shadow: 0px 0px 12px #333;\">          <img src=\"{{image_url}}\">          <div style=\"position: relative\">        <form action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" name=\"_xclick\" target=\"_blank\" style=\"margin: 18px; display: inline-block;\">          <input name=\"cmd\" type=\"hidden\" value=\"_xclick\">          <input name=\"business\" type=\"hidden\" value=\"alllovebling@gmail.com\">          <input name=\"currency_code\" type=\"hidden\" value=\"USD\">          <input name=\"item_name\" type=\"hidden\" value=\"{{text_description}}\">          <input name=\"amount\" type=\"hidden\" value=\"{{price}}\">          <input alt=\"Make payments with PayPal - it's fast, free and secure!\" border=\"0\" name=\"submit\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but5.gif\" type=\"image\">        </form>          </div>        </span>      </div>    </div>    <div class=\"row\">      <div class=\"span\" style=\"width: 100%; text-align: center\">        <h3>{{Product name}}</h3>      </div>    </div>";
        private void button7_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            string strProducts = "<div class=\"row\" style=\"width:100%; background-color:#C9C9C9; padding:24px 10px;\">";
            string strRow = "</div><div class=\"row\" style=\"width:100%; background-color:#C9C9C9; padding:24px 10px;\">";
            ProductTemple =
            "<div class=\"span\" style=\"width: 30%; text-align:center;\">        <span style=\"display: inline-block; position: relative; background: white; border: 6px solid white; border-radius: 2px; box-shadow: 0px 0px 12px #333;\">          <img src=\"{{image_url}}\">          <div style=\"position: relative\">        <form action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" name=\"_xclick\" target=\"_blank\" style=\"margin: 18px; display: inline-block;\">          <input name=\"cmd\" type=\"hidden\" value=\"_xclick\">          <input name=\"business\" type=\"hidden\" value=\"alllovebling@gmail.com\">          <input name=\"currency_code\" type=\"hidden\" value=\"USD\">          <input name=\"item_name\" type=\"hidden\" value=\"{{text_description}}\">          <input name=\"amount\" type=\"hidden\" value=\"{{price}}\">     <Br>${{price}}<Br><Br>         <input alt=\"Make payments with PayPal - it's fast, free and secure!\" border=\"0\" name=\"submit\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but5.gif\" type=\"image\">        </form>          </div>        </span>      </div>   ";

            int i = 1;
            foreach (var product in list)
            {
                try
                {
                    var images = StoreApi.Api.GetProductImageUrls(product.SKU);
                    var productinfo = StoreApi.Api.GetProductInfo(product.SKU, _additionalAttributes);
                    strProducts = strProducts + ProductTemple.Replace("{{price}}", productinfo.price.TrimEnd('0'))
                                                             .Replace("{{text_description}}", productinfo.sku)
                                                             .Replace("{{Product name}}", productinfo.name)
                                                             .Replace("{{image_url}}", images[0]);
                    if (i++ > 2)
                    {
                        strProducts = strProducts + strRow;
                        i = 1;
                    }
                }
                catch (Exception)
                {
                }
            }
            var outHTML = MainTemple.Replace("{{products}}", strProducts) + "</div>";
        }

        private void button8_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _onlineListProucts.Count(); i++)
            {
                var product = _onlineListProucts[i];
                var productinfo = StoreApi.Api.GetProductInfo(product.sku, _additionalAttributes);

                string Material = GetAddatribuites(productinfo.additional_attributes,"materials");
                string Theme = GetAddatribuites(productinfo.additional_attributes, "themes");
                string Stone = GetAddatribuites(productinfo.additional_attributes, "stones");
                string Metals = GetAddatribuites(productinfo.additional_attributes, "metals");
                string strSql = "UPDATE Products SET ";
                if (!string.IsNullOrEmpty(Material))
                    strSql = strSql + "Material = '" + Material + "',";
                if (!string.IsNullOrEmpty(Theme))
                    strSql = strSql + "Theme = '" + Theme + "',";
                if (!string.IsNullOrEmpty(Stone))
                    strSql = strSql + "Stone = '" + Stone + "',";
                if (!string.IsNullOrEmpty(Metals))
                    strSql = strSql + "Metals = '" + Metals + "',";
                ProductsDb.DbMysql.UpdateProduts(strSql.TrimEnd(',') + " WHERE SKU = '" + productinfo.sku + "' ");
            }
        }

        private string GetAddatribuites(associativeEntity[] additional_attributes, string strKey)
        {
            foreach (var additional_attribute in additional_attributes)
            {
                if (additional_attribute.key.ToLower() == strKey.ToLower())
                {
                    var options = getCatalogAttributeOptionEntity(strKey);
                    if (options == null)
                    {
                        return additional_attribute.value;
                    }
                    else
                    {
                        foreach (catalogAttributeOptionEntity catalogAttributeOptionEntity in options)
                        {
                            if (catalogAttributeOptionEntity.value == additional_attribute.value)
                            {
                                return catalogAttributeOptionEntity.label;
                            }
                        }
                    }
                }
            }
            return "";


        }

        private catalogAttributeOptionEntity[] getCatalogAttributeOptionEntity(string strKey)
        {
            foreach (DataGridViewColumn column in this.dataGridViewProducts.Columns)
            {
                var catalogProductAttributeEntity = column.Tag as catalogProductAttributeEntity;
                if (catalogProductAttributeEntity != null && catalogProductAttributeEntity.attribute_code.ToLower() == strKey.ToLower())
                    return catalogProductAttributeEntity.options;
            }
            return null;
        }

        private void buttonGetImagsSku_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            if(fileDialog.ShowDialog(this) == DialogResult.OK)
            {
                foreach (var fileName in fileDialog.FileNames)
                {
                    this.textBox1.Text = this.textBox1.Text + fileName+"\r\n";
                }
            }
        }

        private void buttonDownloadMaibeyUrl_Click(object sender, EventArgs e)
        {
            var list = GetUploadList();
            if (list.Count() == 0) return;
            if (list.Count() <= index) return;
            foreach (var product in list)
            {
                var productInfo = StoreApi.Api.GetProductInfo(product.SKU,null);
                product.MaibeyURL = productInfo.url_path;
                ProductsDb.DbMysql.SetProdutMaibeyUrl(product);
            }
        }

    }
}
